Prompt stringlengths 10 31k | Chosen stringlengths 3 29.4k | Rejected stringlengths 3 51.1k | Title stringlengths 9 150 | Tags listlengths 3 7 |
|---|---|---|---|---|
Is there a way to update a column in mysql if value is number only?
ie. `UPDATE myTable SET ColumnA =NewValue WHERE ColumnA isnumeric`
`Column A` is `varchar(25)` and `Column A` value may be text or 1 or 2 or 23...
thank u | Use regular expression to see if your column contains number or anything else
```
WHERE ColumnA REGEXP '[0-9]+'
``` | Use [**REGEXP()**](http://dev.mysql.com/doc/refman/5.5/en/regexp.html#operator_regexp) function
Try this:
```
UPDATE myTable SET ColumnA = NewValue WHERE ColumnA REGEXP '^[0-9]+$'
```
**OR**
```
UPDATE myTable SET ColumnA = NewValue WHERE ColumnA REGEXP '^[[:digit:]]+$'
``` | MySQL: Update a column if value is numeric only | [
"",
"mysql",
"sql",
"regex",
"sql-update",
"numeric",
""
] |
I have a xml column that look like
```
SET @XMLData = '<ArrayOfEntityNested xmlns:i="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://schemas.datacontract.org/2004/07/Gbms.Dto.Bijak">
<EntityNested>
<Id xmlns="http://schemas.datacon... | First of all - please **use appropriate data types!** If your source data is XML - why aren't you using the `XML` datatype?
Also, if you have a `Date` in your table - why isn't that a `DATE` or `DATETIME` type?? And why is the `Number` a `VARCHAR(50)` ??
Makes no sense......
Then: you're not looking at the XML names... | ```
DECLARE @idoc int
DECLARE @doc varchar(1000)
SET @doc ='
<OutLookContact>
<Contact FirstName="Asif" LastName="Ghafoor" EmailAddress1="asifghafoor@my.web.pk" />
<Contact FirstName="Rameez" LastName="Ali" EmailAddress1="rameezali@my.web.pk" />
</OutLookContact>'
--Create an internal representation of the XML docum... | insert data from xml column into temp table | [
"",
"sql",
"sql-server",
"xml",
""
] |
I have a search screen on my app where the users can use up to 4 parameters to search. I have written a stored procedure to facilitate the search.
```
Select
ID,
FirstName,
LastName,
CountryCd,
State,
Zip,
Data1,
Data2,
Data3
From
Customer
Where
((FirstName like @paramfna... | For this query, I would lead the index with `CountryCd` as that is the only column that is guaranteed to be searched. This of course assumes that the selectivity of `CountryCd` is selective for your data.
If you want to get really fancy, you can add a computed column that contains the SOUNDEX of `FirstName` and anothe... | if user would search by first name and country than index would most probably be beneficial. However if a user would use only last name by a search than the index would have to be read entirely - index scan.
Note that index key column order does matter because it tells SQL Server how to logically sort the index. While... | Should I add multiple secondary index to search | [
"",
"sql",
"sql-server",
"performance",
""
] |
In SQL Server 2008 R2 I have some data in a varchar(12) column, it looks something like this:
```
Data:
%%1234
%1765
34566
123
%SDRMH
HJG434
```
I'd like to drop the '%' from all the rows that have it and also only select those which are numbers. I've already tried to use the ISNUMERIC() function, but it looks like t... | You can use a combination of REPLACE and ISNUMERIC to achieve the result set you want:
```
SELECT REPLACE(columnName,'%','') FROM tableName
WHERE ISNUMERIC(REPLACE(columnName,'%','')) = 1
``` | You could use the `REPLACE` function to strip out all the % instances
```
SELECT REPLACE(column_name,'%','');
GO
``` | Select Only Numbers From Varchar column | [
"",
"sql",
"sql-server",
""
] |
I have a db table say, `persons` in Postgres handed down by another team that has a column name say, `"first_Name"`. Now am trying to use PG commander to query this table on this column-name.
```
select * from persons where first_Name="xyz";
```
And it just returns
> ERROR: column "first\_Name" does not exist
Not s... | **Identifiers** (including column names) that are **not** double-quoted are folded to lower case in PostgreSQL. Identifiers created with ***double quotes*** retain upper case letters (and/or syntax violations) and have to be double-quoted for the rest of their life:
```
"first_Name" -- upper-case "N" p... | To quote the [documentation](http://www.postgresql.org/docs/current/interactive/sql-syntax-lexical.html#SQL-SYNTAX-IDENTIFIERS):
> Key words and unquoted identifiers are case insensitive. Therefore:
>
> ```
> UPDATE MY_TABLE SET A = 5;
> ```
>
> can equivalently be written as:
>
> ```
> uPDaTE my_TabLE SeT a = 5;
> ``... | Are PostgreSQL column names case-sensitive? | [
"",
"sql",
"postgresql",
"identifier",
"case-sensitive",
"case-insensitive",
""
] |
I have query that I am searching for a range of user accounts but every time I pass query I will be using multiple id number's first 5 digits and based on that I will searching. I wanted to know is there any other way to re-write this query for user Id range when we use more than 10 userIDs to search? Is there going to... | Actually it is not important how many UserIDs you will pass to the query. The most considerable part is what is selectivity of your query. In other words: how many rows will return your query and how many rows are there in your tables. If the number of returned rows is relatively small then it is good idea to create an... | Generally the use of LIKE makes it impossible for Oracle to use indexes.
If the query is going to be reused, consider creating a synthetic column with the first 5 characters of COL\_ID. Put a non-unique index on it. Put your search keys in a table and join that to that column.
There may be a way to do it with a funct... | how to improve the performance on this type of Query? | [
"",
"sql",
"performance",
"oracle11g",
""
] |
I need to find if a column value contains the following pattern:
```
513-2400-23 - Valid
513-PBS-231 - Valid
521-PB-21 - Valid
52-12-21 - Valid
513-2321 - Not Valid
```
I have tried the following version and many other but they are working for one case but not for other.
```
SELECT CASE
WHEN REGEXP_LIKE('B12-23-... | ```
Select Case WHEN REGEXP_LIKE('B12-23-43',
'^[[:alnum:]]{1,}-[[:alnum:]]{1,}-[[:alnum:]]{1,}$') THEN 'Y'
ELSE 'N' END
FROM DUAL;
```
**UPDATE**
To also cover cases such as this one: `544-445-PBBTS-24.3`, it could be extended as shown below:
```
Select Case When
Regexp_Like('B12-23-43', ... | Assuming that valid pattern requires exactly two dashes, this should work:
```
SELECT CASE
WHEN REGEXP_LIKE('B12-23-43', '^[^-]+-[^-]+-[^-]+$') THEN 'Y'
ELSE 'N' END FROM DUAL;
```
The pattern requires the string to start in one or more non-dashes, then to have a dash, then some more non-dash characters, and ... | REGEXP_LIKE - Find pattern containing special character | [
"",
"sql",
"regex",
"oracle",
""
] |
I need to write a query that returns the latest message in a conversation between two users. I've included the schema and my (failed) attempts in this fiddle: <http://sqlfiddle.com/#!15/322c3/11>
I've been working around the problem for some time now but every time I run any of my ugly queries *a sweet little kitten d... | > ... the latest message in a conversation between two users.
Assuming the users with ID `1` and `3`, like you did in the fiddle, we are interested in the message with the latest `created_at` and `(sender_id, receiver_id)` being `(1,3)` or `(3,1)`.
You can use ad-hoc row types to make the syntax short:
```
SELECT * ... | This provides the latest message between two users, regardless of message direction:
```
SELECT Distinct mes.ID, sendu.Username AS Sender,
recu.Username as Receiver, Body, maxSent as TimeSent
FROM messages mes
INNER JOIN
(
SELECT One, Two, MAX(CREATED_AT) maxSent
FROM
(
SELECT 'Sender'... | How to get the latest message in each conversation of a certain user in SQL? | [
"",
"sql",
"postgresql",
"greatest-n-per-group",
""
] |
I have two tables `test1` and `test2`. What I need is, I would like to update one column in the table `test2` with data from the table `test1`. My query is
```
UPDATE test2 t2
SET t2.name = (SELECT t1.name
FROM test1 t1
WHERE t1.id = t2.mob)
WHERE t2.mob IN (SELECT t1... | The `WHERE` part in your query is absolutely unnecessary because it always evaluates to `TRUE`. So the correct one to update all rows in `t2` is:
```
UPDATE test2 t2
SET t2.name = (SELECT t1.name
FROM test1 t1
WHERE t1.id = t2.mob)
```
Also in PL/SQL Developer transactions are not... | It wold be easier to use [merge](http://docs.oracle.com/cd/E11882_01/server.112/e41084/statements_9016.htm#SQLRF01606) statement:
```
/* test tables */
SQL> create table test1(id1, name1) as
2 select level
3 , dbms_random.string('l', 7)
4 from dual
5 connect by level <= 5;
Table created
SQL>... | update query result not reflecting in table | [
"",
"sql",
"oracle",
""
] |
```
+------+-----------------+
| id | name +
+------+-----------------+
| 1 | David Gilmour |
| 2 | Roger Waters |
| 3 | Li Jen Ho |
+------+-----------------+
```
Current format of names is `firstName lastName` and I want to change it to `lastName firstName` and I want to that in one ... | Try this:
```
select concat(last_name," ",first_name) as FullName
from
(
select SUBSTRING_INDEX(SUBSTRING_INDEX(name, ' ', 2), ' ', -1) AS last_name,
SUBSTRING_INDEX(SUBSTRING_INDEX(name, ' ', 1), ' ', -1) AS first_name
from your_table
) tab
```
See a sample here
<http://sqlfiddle.com/#!2/cd4ee/4>
**EDIT:**
Then ... | I know I am late to the party but there is a better solution that can handle an unknown number of results.
[GROUP\_CONCAT](https://dev.mysql.com/doc/refman/8.0/en/group-by-functions.html#function_group-concat)
```
SELECT student_name,
GROUP_CONCAT(DISTINCT test_score
ORDER BY test_score DESC SEPARATO... | Explode and implode strings in mysql query | [
"",
"mysql",
"sql",
""
] |
I've got a SQL statement (SQL Server Management Studio) that I'm passing data into a where-statement into via a dashboard software. The users can select the year (2013 or now 2014) and also the month (which gets passes as a numeric value - so December = 12). I need to adjust the statement to where I get the last 3 mont... | There are two solutions for this.
* Modify your current where statement and add a condition to check for this case.
* Use `DATEADD` function. Present in comments and other answer(s).
**Modifying your where to add Condition**
Note: Minor error may exists since I need to check if January has month value of zero or 1.
... | I do not have a running SQL Server instance to test this solution but I would suggest constructing a date and using the built in functions to calculate the previous date as those already take into consideration the multiple years etc.
```
Declare @requestDate date = DATEFROMPARTS('@Request.parmYear', '@Request.par... | Last 3 Months Where Statement | [
"",
"sql",
"sql-server",
"where-clause",
"rolling-computation",
""
] |
I have following table:
**dbPratiche :**

In this i wanted to arrage distinct [Provincia contraente] (first column) and count of that [Provincia contraente] present in [Provincia Agenzia].
Eg.
If I arrange fist column in distinct with following qu... | This query also shows 0 values:
```
SELECT [provincia contraente],
Sum(CASE
WHEN [provincia contraente] = [provincia agenzia] THEN 1
ELSE 0
END)
FROM dbpratiche
GROUP BY [provincia contraente]
```
**UPD:** Here is the query which works for updated question:
```
SEL... | You should be able to,use a group by statement.
```
select [Provincia contraente],count([Provincia Agenzia])
from dbPratiche where [Provincia contraente]=[Provincia Agenzia]
group by [Provincia contraente]
``` | SQL distinctly arranging column query issue | [
"",
"sql",
"sql-server",
"database",
"sql-server-2008-r2",
""
] |
I have created a database in SQL Server 2008 R2 and front end in MS Access 2003 which is `.adp` file format. This application uses Devnagari Unicode fonts for labels and data in database.
The back end has a table `tblBookInfo` for storing Unicode data.
When I write a query to find all records starting from particular... | In my tests, if `NVARCHAR` data type is used with `Indic_General_100_CI_AI` collation then `LIKE` will returns required results:
```
SELECT *
FROM (
SELECT N'क' UNION ALL
SELECT N'कु' UNION ALL
SELECT N'how (strange!)'
) x (Author)
WHERE x.Author COLLATE Indic_General_100_CI_AI
LIKE N'क%' ... | Can you not just use the `OR` operator:
```
SELECT *
FROM tblbookinfo info
WHERE
(Language = 1) AND
(Type = 1)
AND
(
(Author LIKE N'क%')
OR
(Author LIKE N'"कु%')
)
``` | Unicode T-SQL like not returning expected all records | [
"",
"sql",
"sql-server",
"t-sql",
"unicode",
""
] |
I am using mysql database. I have a database lms\_system with table supplier\_details. How can i query to display the supplier id, supplier name and contact, If phone number is null then display ‘No’ else display ‘Yes’ with alias name “PHONENUMAVAILABLE”. | There are a few ways to do that
```
SELECT id, name, contact, IF(phone IS NULL, 'No', 'Yes') phonenumavailable
FROM supplier_details
```
or
```
SELECT id, name, contact, CASE WHEN phone IS NULL THEN 'No' ELSE 'Yes' END phonenumavailable
FROM supplier_details
```
or
```
SELECT id, name, contact, ELT((phone IS N... | ```
SELECT
......
, IF(phone_number is null, 'NO', 'YES')
FROM ....
``` | display different text by checking null or not | [
"",
"mysql",
"sql",
""
] |
Hi I am trying to get (current Datetime - Years).
Below is my Query..
```
print getdate()
print (getdate()-(365.25*7))
Result:
Dec 30 2013 10:47AM
Dec 30 2006 4:52PM
```
is giving correct result.
But When i try
```
print getdate()
print (getdate()-year(7))
Result:
Dec 30 2013 10:52AM
Oct 17 2008 10:52AM... | Try this
```
print getdate()
print DATEADD(Year, -7, GETDATE())
``` | Rather use [DATEADD](http://technet.microsoft.com/en-us/library/ms186819.aspx) with the datepart set to `YEAR`.
> Returns a specified date with the specified number interval (signed
> integer) added to a specified datepart of that date.
Something like
```
SELECT GETDATE() Today, DATEADD(YEAR,-7,GETDATE()) Today7Year... | SQL Select - Current Date - 7 Year | [
"",
"sql",
""
] |
I'm a bit confused about permissions in SQL
I have created a medical database.
As a script I'm creating a doctor role and I want to say they can perform updates on tables 1,2 and 3.
The database though actually contains 5 tables.
does it mean that they wont be able to update 4 and 5 ?
or will i have to explicitly ... | Unless the role was made dbo, db\_owner or db\_datawriter, it won't have permission to edit any data. If you want to grant full edit permissions to a single table, do this:
```
GRANT ALL ON table1 TO doctor
```
Users in that role will have no permissions whatsoever to other tables (not even read). | SQL-Server follows the principle of "Least Privilege" -- you must (explicitly) grant permissions.
'does it mean that they wont be able to update 4 and 5 ?'
If your users in the doctor role are *only* in the doctor role, then yes.
However, if those users are **also in other roles** (namely, other roles that do have a... | SQL permissions for roles | [
"",
"sql",
"sql-server",
""
] |
I have the below table, pretty simple.
```
==========================================================================
attendanceID | agentID | incurredDate | points | comment
==========================================================================
10 | vimunson | 2013-07-22 | ... | After reviewing multiple results I was able to come up with something that is what I expect. I have entered more data and the below syntax. I liked the idea of the cursor but it was not ideal for my use, so I did not use it. I did not want to use `CASE` or any `JOINS` since they can be complex.
<http://sqlfiddle.com/#... | The way variables `@r` and `@_date` are passed around relies on a specific order in which certain parts of the query are evaluated. That's a risky assumption to make in a query language that is declarative rather than imperative. The more sophisticated a query optimizer is, the more unpredictable the behaviour of this ... | Null Values during Query | [
"",
"mysql",
"sql",
"select",
"stored-procedures",
"join",
""
] |
I have searched and gone through the available topics similar to mine. But, failed to find that satisfies my requirements. Hence, posting it here.
I have four tables as follows:
```
"Organization" table:
--------------------------------
| org_id | org_name |
| 1 | A |
| 2 ... | When doing things like this you should build your query up logically, so to start get all your resources and props from organisation A
```
SELECT r.res_name,
r.res_prop
FROM Resource r
INNER JOIN `member-resource` mr
ON mr.res_id = r.res_id
INNER JOIN Members m
ON m.... | I'm not entirely sure I understand what you are looking for, but I think this should work:
```
SELECT Resource.res_name,
COUNT(DISTINCT Resource.res_prop) AS res_prop_count
FROM Resource
INNER JOIN member_resource
USING (res_id)
INNER JOIN Members
USING ... | Complex MySQL query for specific problemm | [
"",
"mysql",
"sql",
"select",
"join",
"group-by",
""
] |
I have mysql code for fetch all my menus from MENU table (working properly):
```
$sql = "SELECT id, category_id, menu_name, image_id
from menu
where restaurant_id = '" . (int) $_SESSION['uid'] . "' && status='1'";
```
But I need data from second table as well. From ICON(table) where is ID value same... | try this
```
SELECT m.id, m.category_id, m.menu_name, m.image_id , i.file_url
FROM menu m
INNER JOIN icon i
ON i.id = m.image_id
WHERE m.restaurant_id = '" . (int) $_SESSION['uid'] . "'
AND m.status='1'
``` | You need to use a JOIN statement for that.
<http://www.sitepoint.com/understanding-sql-joins-mysql-database/> | Load parameter from second mysql table when ID equals | [
"",
"mysql",
"sql",
""
] |
I have a table of links. If the link was generated and then the next day it is still in the table than I want to delete it. If there are multiple rows I want to remove each row.My query is:
```
DELETE FROM resetpassword WHERE expiry_timestamp < DATEADD(day, -1, GETDATE())
```
but this gives me an error:
```
com.web.... | Note: this is a DB2 specific answer.
Okay, this post here: <http://www.dbforums.com/db2/1637371-help-there-dateadd-function-db2.html>
(and this post agrees): <http://www.ibm.com/developerworks/data/library/techarticle/0211yip/0211yip3.html>
says you can do:
```
DELETE FROM resetpassword WHERE expiry_timestamp < ... | If expiry\_timestamp is defined as a timestamp, you should
```
DELETE FROM resetpassword WHERE expiry_timestamp < CURRENT TIMESTAMP - 1 day
```
It is generally better to avoid type conversion (such as timestamp to date) unless there is some need to do so. | Delete records that are older than a day | [
"",
"sql",
"db2",
""
] |
I have a temp table declared
```
declare @tmptable(
value nvarchar(500) not null
);
```
I use a function to insert values into that temp table.
I am trying to figure out how to update a table using the values of @tmptable
```
insert into t1 (
active
,SchoolId
,inserted
)
select
1
... | ```
INSERT INTO t1
(
ACTIVE
,SchoolId
,INSERTED
)
SELECT 1
,temp.value
,@insertedDate
FROM @tmptable temp;
``` | Try this one -
```
INSERT INTO dbo.t1
(
Active
, SchoolId
, Inserted
)
SELECT
1
, t.value
, @insertedDate
FROM @tmptable t;
``` | Inserting temp table values into a table. | [
"",
"sql",
"sql-server",
"t-sql",
""
] |
Consider following subquery. This query retrieves all the personalIds of employees who have more then 1 'IDKleerkastPersoon' in their possession. For this query i'm useing a **COUNT**() statement in my **HAVING** Clause. This subuqery returns all the the PersonalIds for there employees.
```
(SELECT DISTINCT Persoo... | Store the result of first subquery in a table variable and then use it in your final query. Also no need of Order By clause in the subquery unless you are using TOP. | Well If I get what you are after something like
```
SELECT dbo.Persoon.Stamnr, dbo.Persoon.Naam, dbo.Persoon.Voornaam, dbo.Refter.RefterOmschrijving, dbo.Kleedkamer.KleedkamerOmschrijving, dbo.Kleerkast.KleerkastOmschrijving
FROM dbo.KleerkastPerPersoon
inner join (your original query) SomeSuitableAlias
On SomeSuitabl... | SQL subQuery with COUNT() in WHERE/HAVING Statement | [
"",
"sql",
"sql-server",
"count",
""
] |
I have a column with different values :
```
1
2
4
8
```
I want to create a new column in the same table based on these values.
For example, if the value is `1 or 4`, I want to display the corresponding line in `OK` and `NOT OK` for the rest.
Like:
```
1 OK
2 NOT OK
4 OK
8 NOT OK
```
I think we should use an... | Better use **[Case](http://dev.mysql.com/doc/refman/5.0/en/case.html)** statement.
```
SELECT
Case when id in (1,4) Then 'Ok' Else 'Not Ok' End as Myfield
FROM MyTable
```
**[Fiddle](http://sqlfiddle.com/#!2/4c37b/3)** | **Since you say "I want to display" I'll give you some If Snippets**
This is how it works, Simply for ex:
```
SELECT IF(field= '1', 'OK', 'NOT OK') as Myfield
FROM MyTable
```
or
```
SELECT IF(field= '1', 'OK', IF(field= '4', 'OK', 'NOT OK')) as Myfield
FROM MyTable
;So here the result will be `OK` if there is a... | Create SQL column relative to another | [
"",
"mysql",
"sql",
"heidisql",
""
] |
I am writing a SQL query to select row, where a field with space separated numbers contains a single number, in this example the 1.
Example fields:
* `"1 2 3 4 5 11 12 21"` - match, contains number one
* `"2 3 4 6 11 101"` - no match, does not contain number one
The best query so far is:
```
$sql = "SELECT * from "... | Try:
```
WHERE brands REGEXP '[[:<:]]1[[:>:]]'
```
`[[:<:]]` and `[[:>:]]` match word boundaries before and after a word. | You don't need regex: You can use `LIKE` if you add a space to the front and back of the column:
```
SELECT * from $table
WHERE CONCAT(' ', brands, ' ') LIKE '% 1 %'
ORDER BY name
``` | finding a number in space separated list with REGEXP | [
"",
"mysql",
"sql",
"regex",
""
] |
My problem is in the first subquery select. I am being told that I am returning multiple rows.
```
$sql = "SELECT
messages.message_id
, messages.sent_timestamp
, messages.content
, messages.subject
, users.user_name
, (SELECT thread_participants.user_id
FROM thread_participants
WHERE thread... | One way I found of doing it:
```
$sql = "SELECT
messages.message_id
, messages.sent_timestamp
, messages.content
, messages.subject
, users.user_name
, tp.user_id as thread_participants
, (SELECT users.user_name FROM users WHERE users.user_id = thread_participants && users.user_id != mess... | You can use `GROUP_CONCAT()` function to get all **userIds** in single field
Try this:
```
$SQL = "SELECT
messages.message_id
, messages.sent_timestamp
, messages.content
, messages.subject
, users.user_name
, (SELECT GROUP_CONCAT(thread_participants.user_id)
FROM thread_participants
WHERE... | mysql subquery returns multiple rows | [
"",
"mysql",
"sql",
"select",
"subquery",
"group-concat",
""
] |
I have an ID column which it supposed to set to auto-increment but I forgot to set in when creating the database. Let's say the ID is from 1 - 20. I used the select Max() Sql statement to get the largest ID:
```
SELECT MAX(id) FROM Table_Name;
```
It supposed to return me 20. However, it returns me 9. I also realized... | Try this:
```
SELECT TOP 1 Id FROM Table ORDER BY Convert(INT, id) DESC
``` | The issue is likely that the ID column is a varchar field, so 9 is greater than 10.
```
select max(convert(int, id)) from Table
``` | SQL statement to get largest ID from database column | [
"",
"sql",
"database",
""
] |
What is the proper way to query all data on current date? a function in mysql that will get the current date in 12:01 am and current date 11:59 pm
```
select * from tb_data where date between currentdate_starts and currentdate_ends
``` | Try using CURDATE()
```
SELECT field FROM table WHERE DATE(column) = CURDATE()
select * from tb_data where DATE(date) = CURDATE()
```
Documentation: [CURDATE](http://dev.mysql.com/doc/refman/5.6/en/date-and-time-functions.html#function_curdate) | Without using `DATE(column) = CURDATE()`
```
SELECT * FROM tb_data WHERE date between concat(curdate(),' ','00:00:00') AND concat(curdate(),' ','23:59:59')
```
[more info](https://stackoverflow.com/questions/14104304/mysql-select-where-datetime-matches-day-and-not-necessarily-time) | MySQL query value where current date | [
"",
"mysql",
"sql",
"date",
"datetime",
"select",
""
] |
I have 3 tables: icon, product and menu.
```
Product-
id | menu_id
----------
1 | 1
2 | 1
3 | 2
4 | 2
5 | 3
Menu-
id | image_id
----------
1 | 10
2 | 11
3 | 12
Icon-
id | file_url
----------
10 | www.example/....
11 | www.example/....
12 | www.example/....
```
So when I try to list each menu with as... | You can add another join, i.e. something like that:
```
$sql = "SELECT p.id, m.menu_name, m.image_id, i.file_url
FROM product p
INNER JOIN menu m ON m.id = p.menu_id
INNER JOIN icon i ON i.id = m.image_id
WHERE ... ";
``` | You can join more than 2 tables, the syntax is the exact same, so what you'd want is:
```
SELECT
<stuff, including i.file_url>
FROM
menu m
JOIN product p on m.id = p.menu_id
JOIN icon i on i.id = m.image_id
``` | Join 3 tables in mysql | [
"",
"mysql",
"sql",
""
] |
I have a list of values that, i.e.
```
in ('1xxx','12xx','21xx','98xx','00xx')
```
I want to use for an insert script. How can a write a for loop in SQL Server using each value within the loop? I'm think something like.
```
For value in ('1xxx','12xx','21xx','98xx','00xx')
select value
endloop;
```
**Im trying to... | You don't need expensive loops, cursors or functions to build a set from these values you've been handed manually.
```
DECLARE @start DATE = '20130101', @now DATETIME2(7) = CURRENT_TIMESTAMP;
;WITH months AS
(
-- we need 12 months
SELECT TOP (12) m = number FROM master.dbo.spt_values
WHERE type = 'P' ORDER BY... | If you have comma delimited string use some of these 4 functions that returns table (<http://blogs.msdn.com/b/amitjet/archive/2009/12/11/sql-server-comma-separated-string-to-table.aspx>).
Insert returned data in temp table with identity column (1,1).
After that loop through table with cursor or using previously create... | ForEach Loop in SQL Server | [
"",
"sql",
"foreach",
"sql-server-2012",
"iteration",
""
] |
The requirement is to exclude ItemA and ItemE from the search as they contain value 1 in columnB.

The final result should be something like this

I have tried `SELECT * FROM my_ta... | Try:
```
SELECT *
FROM tablee
WHERE ColumnA NOT IN (
SELECT columnA FROM tablee
WHERE columnB = 1
);
```
or
```
SELECT *
FROM tablee t1
WHERE NOT EXISTS(
SELECT 1 FROM tablee t2
WHERE t2.columnB = 1 and t1.columnA = t2.columnA
);
``` | First we make a sub-query that looks for rows with ColumnB = '1'. Then we left join that sub query to our main table on matching ColumnA names. Items that have a different row with a '1' in ColumnB will now have a value there, other rows will just have NULL because of the left join. We then use a where to only find the... | sql select query excluding certain values | [
"",
"sql",
"oracle",
""
] |
I'm not that great with SQL Server, but I'm trying to do some behind the scenes work to create some functionality that our EMR system lacks - copying forms (and all their data) between patients.
In SQL Server 2008 R2 I have three tables that deal with these forms that have been filled out:
```
**Table 1**
encounter_i... | Made a little fiddle as an example, [here (link)](http://sqlfiddle.com/#!3/9f637/3/0)
The solution is perhaps needlessly complex but it offers a good variety of other useful stuff as well, I just wanted to test how to build that dynamically. The script does print out the commands, making it relatively easy to remove t... | I always like creating sample tables in [tempdb] so that the syntax is correct. I created tables [t1], [t2], and [t3]. There are primary and foreign keys.
If you have a well developed schema, ERD (entity relationship diagram) <http://en.wikipedia.org/wiki/Entity-relationship_diagram> , these relationships should be in... | SQL - Copy Data Within Same Table | [
"",
"sql",
"sql-server",
""
] |
I'm trying to make my SQL query work and I fail, so I decided to ask more experienced and familiar with SQL people since I'm not so.
What I have: 2 tables in my DB, one is "DEV" table that contains: `id, lat, lon, login, password` second one is "TASK" table which contains: `id, lat, lon, address, id_dev`. Id\_dev is a... | If you want the 'dev' records with no 'task' you shouldn't use `INNER JOIN` as that brings back the intersection of the sets.
One option is to use a `LEFT JOIN`, so something like:
```
SELECT dev.*
FROM dev
LEFT JOIN task
ON dev.id=task.id_dev
WHERE task.id_dev IS NULL
ORDER BY d... | ```
SELECT * FROM `dev` INNER JOIN 'task' ON dev.id=task.id_dev ORDER BY dev.id;
```
Do not use single quote `'` on `task`. Query should look like:
```
SELECT * FROM `dev` INNER JOIN `task` ON dev.id=task.id_dev ORDER BY dev.id;
``` | INNER JOIN does not work for me | [
"",
"mysql",
"sql",
"select",
"join",
"left-join",
""
] |
Currently i facing a problem to display search parameter in 'Like' statement as 1 new column. my SQL code is as below:
```
Select A.Description from table A Where A.Description like ('%Battery%')
```
The Output:
```
Description
12V Battery
9V Battery
5V Battery
```
The Output i want was:
```
Description Desc... | Something like:
[SQL Fiddle](http://sqlfiddle.com/#!4/4b96f/1)
**Oracle 11g R2 Schema Setup**:
```
CREATE TABLE table_name ( Description ) AS
SELECT '9V Battery' FROM DUAL
UNION ALL SELECT '12V Battery' FROM DUAL
UNION ALL SELECT '24V Battery' FROM DUAL
UNION ALL SELECT 'Torch' FROM DUAL
UNION ALL SELECT '... | how about including it in the `SELECT` statement?
```
SELECT A.Description ,
'Battery' AS Description_1
FROM table A
WHERE A.Description LIKE '%Battery%'
``` | Display Search Parameter As Column | [
"",
"sql",
"oracle",
"oracle11g",
""
] |
I am using a very complex UNION ALL query to parse out information from an XML import into an existing Access table. I am running into an issue is when I am attempting to write the query to only populate the table if the field is not null. I have tried using an IIF statement at the beginning and I many different iterat... | If `transectA` is text datatype and you want your query to ignore rows with Null or zero-length strings in that column ...
```
WHERE Len([transectA]) > 0
``` | If the two queries that you're UNIONing together are meant to represent mutually exclusive sets, then you need to indicate that.
In each query you select from the same table, but with a different where clause. In the first query you say where transectA is not null. TrasnectP can still be null here, and those records w... | WHERE Is Not Null Query | [
"",
"sql",
"ms-access",
""
] |
I have a table containing information about retail stores. I have a list of retail chain names (WalMart, Target, Eatons, etc...) When the user selects one I basically run a query to find anything having to do with that chain.
```
SELECT * FROM stores WHERE store_name LIKE '%$chain%' ORDER BY store_name ASC
```
For ex... | Yes, you can do the following:
```
SELECT * FROM stores WHERE store_name LIKE '%$user_input%'
AND store_name LIKE '%Walmart%'
ORDER BY store_name ASC
``` | Sure, you can just add two LIKE clauses:
```
SELECT * FROM stores
WHERE store_name LIKE '%$chain%'
AND store_name LIKE '%$user_input%'
ORDER BY store_name ASC
``` | Multiple LIKE statements in SQL | [
"",
"sql",
""
] |
Here I want to take all the children including parent using parentid what is wrong.Am getting Exception connect by in loop user data.
Thanks in Advance.
**Query :**
```
select *
from rdt_organization
connect by prior parentid = 102;
```
**Table Content :**
```
id parentid
102 null
103 102
112 102
104 103
... | You need to connect the rows to the `PRIOR` row using id and parentid, and use `START WITH` to decide where to start;
```
SELECT *
FROM rdt_organization
START WITH id = 102
CONNECT BY PRIOR id = parentid
```
[An SQLfiddle to test with](http://sqlfiddle.com/#!4/c3032/1). | Start with is missing
```
select *
from rdt_organization
start with id = 102
connect by prior id = parentid;
``` | Oracle Connect By SQL Query | [
"",
"sql",
"oracle",
""
] |
I currently have two stored procedures that are meant to do the same thing. I was given two ideas on how to retrieve a fairly complex set of data, so I wrote them both and now I need to determine which one is more efficient.
I have tried using Sql Profiler, client statistics, and reviewing Execution Plans, but the res... | With more test data the timing might stabilize because caching plays less of a role. Also the difference between the procs will become more pronounced. You will also be able to observe their asymptotic scaling behaviors. Different kinds of joins and indexing strategies scale differently with added data.
Increase the a... | What you need is to have the execution plan of both queries to be able to determine which one is better.
This is a good article on this topic:
<http://sqlmag.com/blog/comparing-execution-plans> | Is there a way to consistently determine which of two stored procedures is faster? | [
"",
"sql",
"sql-server",
"performance",
"stored-procedures",
""
] |
This is my first time developing a database and first time using MS Access! I am trying to append 1 new record to a table via a form linked to a query.
```
Private Sub cmdAdjustStock_Click()
'Declare Vars
Dim newqty As Long
Dim Qty As Control
Dim change As Control
Dim BoxType As Control
Dim sql As String
'Set form co... | Inspect the `INSERT` statement you're asking Access to execute.
```
sql = "INSERT INTO tblHistory (BoxType, QtyChange, NewQty) VALUES ('&BoxType&','&change&','&newqty&')"
Debug.Print sql
```
Run the code and examine the `INSERT` statement in the Immediate window. You can go there with `Ctrl`+`g`.
And you can copy th... | This isn't going to work:
```
sql = "INSERT INTO tblHistory (BoxType, QtyChange, NewQty) VALUES ('&BoxType&','&change&','&newqty&')"
```
Try changing it to:
```
sql = "INSERT INTO tblHistory (BoxType, QtyChange, NewQty) VALUES ('" & BoxType & "','" & change & "','" & newqty & "')"
``` | Fail to Append due to Key Violations | [
"",
"sql",
"ms-access",
"ms-access-2007",
"vba",
""
] |
I encountered an odd situation where appending `OPTION (RECOMPILE)` to my query causes it to run in half a second, while omitting it causes the query to take well over five minutes.
This is the case when the query is executed from Query Analyzer or from my C# program via `SqlCommand.ExecuteReader()`. Calling (or not c... | There are times that using `OPTION(RECOMPILE)` makes sense. In my experience the only time this is a viable option is when you are using dynamic SQL. Before you explore whether this makes sense in your situation I would recommend rebuilding your statistics. This can be done by running the following:
```
EXEC sp_update... | Often when there is a drastic difference from run to run of a query I find that it is often one of 5 issues.
1. **STATISTICS** - Statistics are out of date. A database stores statistics on the range and distribution of the types of values in various column on tables and indexes. This helps the query engine to develop ... | OPTION (RECOMPILE) is Always Faster; Why? | [
"",
"sql",
"sql-server",
"sql-server-2008",
"compilation",
"query-hints",
""
] |
I have two tables, and a query that looks like this::
```
select * from table_1
where x.column_1 in (
select column_2 from table_2
where column_3 = 'foo')
```
which almost works for me; there are nulls in `column_1` and `column_2` that I want to be considered as matches.
I could write a `union`with this:
``... | Try this
```
select * from table_1
where coalesce (column_1,'special value') in
(
select coalesce (column_2,'special value')
from table_2
where column_3 = 'foo'
)
```
Of course `'special value'` should not be contained in `column_3` of `table_2` and must be compatible to the d... | Would this not work for you?
```
select *
from table_1 t1
where EXISTS (
select 1
from table_2 t2
where t2.column_3 = 'foo'
AND (
t1.column_1 = t2.column_2
... | What's the most elegant way to deal with nulls | [
"",
"mysql",
"sql",
""
] |
I'm trying to update a record at the same time I select it. In Oracle SQL Developer, the below query works. However, when I execute it from within a CFQUERY tag in ColdFusion, I get an error (see below). I found this stack overflow ([ORA-06550 and PLS-00103](https://stackoverflow.com/questions/4270818/ora-06550-and-pls... | **EDIT**:
you can see here that, after the semicolon in declare block, CF pushed the query to the db layer, and oracle in turn replied back stating, I see a space instead of a begin keyword! Sure we have to push the block completely, and this should work.
```
<cfset variables.plsql = "
DECLARE
record_id scpriceque... | Do two queries, this should answer your question: <https://stackoverflow.com/a/1883117/3112803>
Hope that helps.
Since you are only doing one update and one select then the cftransaction tags are not needed. But if you were doing multiple add/update/deletes then you would want the cftransaction tag so if a error happe... | Oracle SQL RETURN INTO Fails within CFQUERY (ORA-06550/PLS-00103) | [
"",
"sql",
"oracle",
"coldfusion",
""
] |
I have 2 database tables:
`customers` and `customers_1`
I have 100 customers in the `customers` table but only 99 customers in the `customers_1` table. I would like to write a query that will compare the 2 tables and will result in the missing row.
I have tried this following SQL:
`select * from customers c where i... | Your query shouldn't work this way. You have to compare one column to another and use `NOT IN` instead of `IN`:
```
select *
from customers c
where customerid not in (select customerid from customers_1)
```
However, Since you are on SQL Server 2008, you can use [`EXCEPT`](http://technet.microsoft.com/en-us/library/... | This is easy. Just join them with a left outer join and check for `NULL` in the table which has the 99 rows. It will look something like this.
```
SELECT * FROM customers c
LEFT JOIN customers1 c1 ON c.some_key = c1.some_key
WHERE c1.some_key IS NULL
``` | Compare 2 tables and find the missing record | [
"",
"sql",
"sql-server-2008",
"t-sql",
""
] |
I am very unfamiliar with advanced SQL.
Lets say I have the following table (in Access - using Jet 4.0 OLEDBAdapter in VB.NET).
Table - Items
```
ID Date Account Amount
----- ------ ------- ------
1 1/1/2013 Cash 10.00
2 2/1/2013 Cash 20.00
3 1/2/2013 Cash 30.00
4 2/2... | Since there are exactly 12 months in a year, you do not need to pivot; just calculate the sum for each month:
```
SELECT Account,
Sum(IIF(Month(Date)=01, Amount, 0)) AS Jan,
Sum(IIF(Month(Date)=02, Amount, 0)) AS Feb,
Sum(IIF(Month(Date)=03, Amount, 0)) AS Mar,
Sum(IIF(Month(Date)=04, Amount, 0)) AS Ap... | Using your sample data, this is the output I got from the query below with Access 2010.
```
Account 2013-01 2013-02
------- ------- -------
Card $120.00 $140.00
Cash $40.00 $60.00
```
My totals don't match your expected output. I suspect your date values were *d-m-yyyy* format, but my US locale interpreted th... | SQL statement to generate a table of totals by month | [
"",
"sql",
"vb.net",
"ms-access",
""
] |
I have following query:\
```
SELECT *
FROM (SELECT 1 CntCol, CONVERT(CHAR(3), [data out (no val#vuoto)], 0) month,
( [gruppi min (gg flusso/decorrenza-->out)] )
FROM dbpratiche
WHERE compagnia = 'GENERALI INA ASSITALIA'
AND stato = 'OUT ATTIVATA'
... | try this code:
```
SELECT *
FROM (SELECT 1 CntCol, CONVERT(CHAR(3), [data out (no val#vuoto)], 0) month,
( [gruppi min (gg flusso/decorrenza-->out)] )
FROM dbpratiche
WHERE compagnia = 'GENERALI INA ASSITALIA'
AND stato = 'OUT ATTIVATA'
AND [data out (no val... | I solved it myself through:
```
select * from
(
SELECT 1 CntCol, CONVERT(CHAR(3), [data out (no val#vuoto)], 0) month,
( [gruppi min (gg flusso/decorrenza-->out)] )
FROM dbpratiche
WHERE compagnia = 'GENERALI INA ASSITALIA'
AND stato = 'OUT ATTIVATA'
... | Pivoting pivoted table | [
"",
"sql",
"sql-server",
"sql-server-2008-r2",
""
] |
I have a table for comments :
```
+----------+---------------------+----------+
| match_id | timestampe | comment |
+----------+---------------------+----------+
| 100 | 2014-01-01 01:00:00 | Hi |
| 200 | 2014-01-01 01:10:00 | Hi1 |
| 300 | 2014-01-01 01:20:00 | Hi2 |
| 10... | You can do it this way.
This is pretty optimal too.
```
SELECT c.comment, m.*
FROM
comments c
JOIN
(
SELECT t.match_id, max(t.timestampe) as maxtimestamp, count(t.match_id) as comments_no
FROM comments t
GROUP BY t.match_id
) m on c.match_id = m.match_id and c.timestampe = m.maxtimestamp
```
[SQL Fiddl... | I'm not sure about MySQL but Oracle supports window functions, so I can write something like:
```
select first_value(comment) over (order by timestamp desc)
from comments
``` | How to get the value of a row with Max aggregation function? | [
"",
"mysql",
"sql",
"aggregate-functions",
""
] |
We store date data as int instead if date formart with SQL server 2008.
Why they won't store date as date format type?
Is there any advantage? | Prior to SQL Server 2008 it was common (perhaps even best practice) to use integer encoded dates in warehouses, i.e. 20130106
It was storage efficient (4 bytes) and human readable.
Now that there is a (3 byte) `Date` datatype, I would use that in new development.
(splitting date and time in either scheme is importan... | Well, you would need to ask the people that put the guidelines/rules together to be certain. I, for one, would rather use the DBMS date formats since there are a lot of things you can do with them beyond simple comparisons, and in a way that's usually more efficient.
I seem to recall that versions of SQL Server prior ... | What is the advantage of having date as int? | [
"",
"sql",
"sql-server-2008",
""
] |
Using SQL Server 2008 R2 when I enter the following query:
```
SELECT CAST(POWER(2.0, 63.0) AS BIGINT);
```
Which yields the result:
```
9223372036854775800
```
However, using the Windows desktop calculator and raising 2 to the 63 yields:
```
9223372036854775807
```
Can someone please explain the difference -- or... | The range of `BIGINT`in MS Sql Server is:
```
-2^63 (-9,223,372,036,854,775,808) to 2^63-1 (9,223,372,036,854,775,807)
```
And your calculator is giving you the wrong number, because 2^63 can't have an odd number for its right-most digit.
The `POWER` function in SQL Server (<http://technet.microsoft.com/en-us/librar... | Power will be returning a FLOAT. Floating point numbers are not accurate beyond certain limits, and will drop a bit of accuracy (if you've ever has a negative 0 problem you'll know what I mean!).
That's what you're getting here... | SQL Server POWER function | [
"",
"sql",
"sql-server",
"sql-server-2008-r2",
"bigint",
""
] |
I'm trying to write a query that takes a list parameter (ie, a single parameter which is a list of values). It appears that this is at least sometimes possible in PostgreSQL (<https://stackoverflow.com/a/10829760/836390>). What I want is something like this:
```
rows, err := db.Query("SELECT * FROM table WHERE id in $... | You can use [pq.Array](https://github.com/lib/pq/blob/master/array.go) with slice parameters nowadays. So the query would look like:
```
rows, err := db.Query("SELECT * FROM table WHERE id in $1", pq.Array([]int{1, 2, 3}))
``` | So it looks like [pq](http://github.com/lib/pq) uses [database/sql](http://golang.org/pkg/database/sql)'s default ValueConverter, which has no ability to handle slices (see the [documentation](http://golang.org//pkg/database/sql/driver/#pkg-variables) for DefaultParameterConverter). | PostgreSQL list parameter in Go (using database/SQL and pq) | [
"",
"sql",
"postgresql",
"go",
"prepared-statement",
""
] |
I'm currently using these sql statements. My table has the field CPaymentType which contains "Cash" or "Check". I can sum up the amount of payments by executing 2 SQL statements as shown below. In this case, the user won't even notice the speed difference when executing 2 sql statements or just 1, however, I don't like... | ```
Select SUM(CASE When CPayment='Cash' Then CAmount Else 0 End ) as CashPaymentAmount,
SUM(CASE When CPayment='Check' Then CAmount Else 0 End ) as CheckPaymentAmount
from TableOrderPayment
Where ( CPayment='Cash' Or CPayment='Check' ) AND CDate<=SYSDATETIME() and CStatus='Active';
``` | ```
select CPaymentType, sum(CAmount)
from TableOrderPayment
where (CPaymentType = 'Cash' and CStatus = 'Active')
or (CPaymentType = 'Check' and CDate <= bsysdatetime() abd CStatus = 'Active')
group by CPaymentType
```
Cheers - | SELECT query with CASE condition and SUM() | [
"",
"sql",
"sql-server",
"sum",
"case",
"conditional-statements",
""
] |
I have a data set for appointments with start and end times for each appointment. I need to calculate the amount of time the appointment lasted in hours, but the two fields are in 24-hour time and formatted as `INTEGER`. To make things even worse they're formatted as both 3 and 4 character integers so `830` and `1630` ... | Since `startTime` and `endTime` are both integers, you can use simple modulo and division to separate minutes and hours.
The following expression will give you `startTime` in minutes:
```
startTime % 100 + (startTime / 100) * 60
```
You can do the same for `endTime` and subtract `endTime` from `startTime` to get an ... | Use a helper function to convert the INT military time to the native DATETIME type of your SQL database:
```
SELECT DATEDIFF(hh, dbo.fnConvertMilitary(StartTime),
dbo.fnConvertMilitary(EndTime)
FROM appointments
```
Refer to @AlonGubkin's great answer for the implementation of dbo.fnConvertMilitary. | Figuring out the difference in hours between two 24-hour times in SQL | [
"",
"sql",
""
] |
Amazon Redshift is based on ParAccel which is based on Postgres. From my research it seems that the preferred way to perform hexadecimal string to integer conversion in Postgres is via a bit field, as outlined in this [answer](https://stackoverflow.com/questions/12375369/convert-hex-string-to-bigint-in-postgres).
In t... | It looks like they added a function for this at some point: [STRTOL](http://docs.aws.amazon.com/redshift/latest/dg/r_STRTOL.html)
> *Syntax*
>
> STRTOL(num\_string, base)
>
> *Return type*
>
> BIGINT. If num\_string is null, returns NULL.
**For example**
```
SELECT strtol('deadbeef', 16);
```
Returns: `3735928559` | Assuming that you want a simple digit-by-digit ordinal position conversion (i.e. you're not worried about two's compliment negatives, etc) I think this should work on an 8.1-equivalent DB:
```
CREATE OR REPLACE FUNCTION hex2dec(text) RETURNS bigint AS $$
SELECT sum(CASE WHEN v >= ascii('a') THEN v - ascii('a') + 10 EL... | Hex string to integer conversion in Amazon Redshift | [
"",
"sql",
"postgresql",
"amazon-web-services",
"hex",
"amazon-redshift",
""
] |
How can I select across multiple rows based on a particular column value. For example I have a structure like this
```
+--+----+-----+
|id|data|count|
+--+----+-----+
|1 |text|30 |
+--+----+-----+
|1 |text|1 |
+--+----+-----+
|1 |text|25 |
+--+----+-----+
|1 |text|12 |
+--+----+-----+
|1 |text|50 |
+--+----... | You should be able to implement a [windowing function](http://www.postgresql.org/docs/current/static/functions-window.html) like `row_number()` to get the top 3 for each `id`:
```
select id, data, "count"
from
(
select id, data, "count",
row_number() over(partition by id order by "count" desc) seq
from yourta... | ```
SELECT "id",data,"count"
FROM
(SELECT "id",data,"count" rank() OVER (partition by "id" ORDER BY "count" DESC) as rn
FROM
your_table) t
WHERE rn <= 3
ORDER BY "id","count" desc
``` | select 3 values for each id based on top values in a count column | [
"",
"sql",
"postgresql",
""
] |
I have two tables
```
TABLE_A
+-------+------------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-------+------------------+------+-----+---------+-------+
| bid | int(10) unsigned | NO | PRI | 0 | |
| uid | int(10) unsigned | NO | PRI | 0 ... | Try this
```
SELECT DISTINCT bid FROM TABLE_A WHERE uid = 123
UNION
SELECT DISTINCT bid FROM TABLE_B WHERE uid = 123
```
**OR**
```
SELECT DISTINCT bid
FROM (SELECT bid FROM TABLE_A WHERE uid = 123
UNION
SELECT bid FROM TABLE_B WHERE uid = 123
) AS A
``` | ```
SELECT ta.bid,
tb.bid
FROM table_a AS ta,
table_b AS tb
WHERE ta.uid = tb.uid
AND ta.uid = 123
GROUP BY ta.bid,
tb.bid
```
Second Method would be
```
SELECT ta.bid,
tb.bid
FROM table_a AS ta
INNER JOIN table_b AS tb
ON ( ta.uid = tb.uid ... | Combine result of two tables | [
"",
"mysql",
"sql",
"select",
"distinct",
"union",
""
] |
I am trying to generate a random 9 digit number
for example `0987654321` note that each digit appear once..
i tried this :
```
select convert(numeric(10,0),rand() * 8999999999) + 10000000
```
it generates but at some point numbers repeat. but it is client need to make sure in 9 digit sequence no number appears twic... | It seems you are trying to generate a 10 digit number. I made it as a varchar because I don't want to supress the first 0 when applies:
```
declare @rnd varchar(10) = ''
;with a as
(
select 0 x
union all
select x + 1
from a where x < 9
), b as
(
select top 10 x from a
order by newid()
)
select @rnd += cast(x as char(1... | As you want to insert these values in to a table, and also check for duplicated. I would do the following:
**1. Create a view to generate a NewId**
```
create view vw_getNewID as select newid() AS [NewId]
```
**2. Generate a TVF**
```
CREATE FUNCTION dbo.fn_GenerateRandomNumber()
RETURNS @r TABLE
(
RandomNumber var... | Generate a random 9 digit number | [
"",
"sql",
"sql-server",
""
] |
I am trying to create a query that calculates credit and debit for each month. the values are in column called SUM and there is a field for each record that says if it is credit or debit (ex\_type). I have manage to get the total sum of all the fields (although it is not correct as well - cos I am just sum all the valu... | Try this with `CASE`
```
Select sum(CASE WHEN ex_type='Debit' THEN `sum` ELSE 0 END) as Debit,
sum(CASE WHEN ex_type='Credit' THEN `sum` ELSE 0 END) as Credit FROM ...
``` | This should work:
```
Select sum(d.sum) as Debit,
(Select sum(c.sum) from acc c where c.ex_type='Credit' and c.month='$month') as Credit
from acc d where d.ex_type='Debit' and d.month='$month'
```
However if you supply more details on other fields one could inner join onto the same table and that may be slightly m... | SQL SUM values where 2 conditions are met | [
"",
"mysql",
"sql",
"sql-server",
"select",
""
] |
I'm working in a centralized monitoring system on Windows 2008 R2, I have installed a PostgreSQL 9.3 to use **psql** from the command line.
When I try to access to some remote Postgres (an 8.4 in my principal case) I have an error with the encoding:
command:
```
psql.exe -h 192.168.114.12 -p 5432 -d db_seros_transac... | Thanks a lot **Craig Ringer**, works, finally works! You are my new idool now!
The steps are:
1. open the cmd
2. `SET PGCLIENTENCODING=utf-8`
3. `chcp 65001`
4. `psql -h your.ip.addr.ess -U postgres` | Windows 10 / Windows server 2016 or later:
* Open `Windows Control Panel`
* Select `Region (and Language)`
* Click `Change system locale`
* `Beta: Use Unicode UTF-8 for worldwide language support`
* Click OK
or
```
[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Nls\CodePage]
"ACP"="65001"
"OEMCP"="65001"
"MACC... | PostgreSQL: encoding problems on Windows when using psql command line utility | [
"",
"sql",
"postgresql",
"command-line",
"character-encoding",
"psql",
""
] |
I was trying to use sqlFetch. The fetch works perfectly when I change the name of my table to have underlines instead of periods. So if I use the command
```
sqlFetch(conn, "HelloWorld_40")
```
It works fine. Unfortunately, my friends are all using the real name of the table
```
sqlFetch(conn, "HelloWorld.40")
```
... | It is a problem with `sqlFetch` which parse table name. Unfortunately it did not handle table quotes, so it's search for table `40` in schema `HelloWorld`. You need to directly call `sqlQuery` (with quoted table name, brackets for MS SQL Server):
```
sqlQuery(dbhandle, "SELECT * FROM [HelloWorld.40]")
```
Side note: ... | put the table name in square brackets:
```
[HelloWorld.40]
``` | table with "." in its name | [
"",
"sql",
"r",
"rodbc",
""
] |
Below is a update query which is to update a table with about 40000 records:
```
UPDATE tableName
SET colA = val, colB = val
WHERE ID IN (select RecordIDs from tableB where needUpdate = 'Y')
```
When the above query is executed, I found out that the below query taken ~ 15 seconds
```
SELECT RecordIDs
FROM tableB
WHE... | The execution plan shows you are using table variables and are missing a useful index.
Keep the existing PK on `@output`
```
DECLARE @output TABLE (
ID INT PRIMARY KEY,
VehicleBrandID INT,
VehicleLicenseExpiryDate NVARCHAR(25),
LicensePlateNo NVARCHAR(MAX),
ContactP... | I suppose you are in one of the 2 cases below:
1/ [STATISTICS are not updated](http://sqlhint.com/sqlserver/how-to/when-update-statistics-flag-2371) due to a some recently modification of in your table. In this case you should execute this:
```
UPDATE STATISTICS tableB
```
2/ I suppose [a wrong query plan is used](h... | SQL IN operator in update query causes a lot of time | [
"",
"sql",
"sql-server",
"sql-server-2012",
""
] |
I'm trying to set up a trigger that will insert certain values from a table and specify other values with the `VALUES` command. Something like the code below:
```
INSERT INTO table_name(ID, Name, Email)
SELECT userID, userName
FROM users_table
WHERE condition1
VALUES ('example@yahoo.com')
```
So as yo... | The `INSERT` command comes in two flavors:
**(1)** either you have all your values available, as literals or SQL Server variables - in that case, you can use the `INSERT .. VALUES()` approach:
```
INSERT INTO dbo.YourTable(Col1, Col2, ...., ColN)
VALUES(Value1, Value2, @Variable3, @Variable4, ...., ValueN)
```
Note:... | something like this,
```
INSERT INTO table_name (ID, Name, Email)
SELECT userID, userName, 'example@yahoo.com' AS Email
FROM users_table
WHERE ..condition1..
``` | SQL Server : is there a way to insert into a table values using both SELECT and VALUES at the same time? | [
"",
"sql",
"sql-server",
"select",
"insert",
""
] |
I have following table:

I wanted to pivot month column and show count of data according to groups of >10,<=06,etc.
Means wanted to show how many counts for >10 in Jun, jan
As folows:
```
Gruppi Min (GG Flusso/Decorrenza-->Out) Jan Feb Mar Apr M... | This worked
```
SELECT *
FROM
(SELECT 1 CntCol, [Gruppi Min (GG Flusso/Decorrenza-->Out)], [month]
FROM #X) TLB
PIVOT
(
COUNT (CntCol)
FOR TLB.[month] IN
( [jan],[feb],[mar],[apr],[may],[jun] )
) AS pvt
```
You need to add a column that should be counted.
Look at the complex example here:
<http://technet.microsoft.... | you can add an autoincrement field to your dbPratiche table(for example id), and then try this code:
```
select * from
(
select [id], [month], [gruppi]
from dbPratiche
)as s
pivot
(
COUNT ([id])
for month in(jun, sep, jul, may, aug)
)as PVT
``` | Pivoting a column and showing data according to count | [
"",
"sql",
"sql-server",
"sql-server-2008-r2",
""
] |
I've an SQL table with this structure
```
Stud Name Score
---------------------
Alex 7
John 5.6
Tom 8.2
Antony 6
George 9
Mathew 7
Jim 5.5
```
I need to find top three students based on score.
So my query is
```
select top 3 * from studtable order b... | You can try using subquery
```
select * from studtable
where score in (select distinct top(3) score from studtable order by score desc)
order by score desc
``` | Try this:
```
select top 3 with ties * from studtable order by score desc
```
This'll get you top 3 including ties.
# [See it in Action](http://www.sqlfiddle.com/#!6/d41d8/13597) | Top 3 rows based on score, but to handle ties | [
"",
"sql",
"sql-server",
"sql-server-2008",
""
] |
I have 4 tables: Foo, Bar, Charlie, & Delta. Tables Charlie, Delta, & Bar all have a foreign key column containing the primary key for a Foo. The foreign key columns have the unique constraint, so no more than 1 of each can be linked to a given Foo. Furthermore, due to how the domain was modeled, there should never be ... | Yes, it could *potentially* be faster to combine them.
This is because you have a chance to avoid going back to Bar multiple times.
The long answer, of course, is that it always depends on your indexing and hardware setup (and everything else :) ).
So it is essential that you actually test the old way against any new ... | Since you're coding in C#, you can use Linq to SQL:
```
var query = from f in Foo
// inner equijoin:
join b in Bar on f.PRIMARY_KEY equals b.FOO
// left outer join:
join tc in Charlie on f.PRIMARY_KEY equals tc.FOO into gc
from c in gc.DefaultIfEmpty()
... | Should I combine these queries, and if so, how? | [
"",
"sql",
"query-optimization",
""
] |
I am still a beginner in SQL and i'm facing an issue. hope you can help me.
I have a table called Department where it has an attribute DEPARTMENT\_NO as its primary key.
```
CREATE TABLE DEPARTMENT(
DEPARTMENT_NO INT NOT NULL,
NAME VARCHAR(25) NOT NULL,
LOCATION CHAR(15),
PRIMARY KEY(DEPARTMENT_NO));
```
I have a... | The standard way to represent a "many to many" relationship is via a "junction" (aka "link") table:
```
CREATE TABLE DOCTOR_DEPARTMENT (
DOCTOR_ID INT REFERENCES DOCTOR(DOCTOR_ID),
DEPARTMENT_NO INT REFERENCES DEPARTMENT (DEPARTMENT_NO),
PRIMARY KEY (DOCTOR_ID, DEPARTMENT_NO)
);
```
Note the key on {DOCTO... | You need an additional table called doctor\_department
```
create table doctor_department
(doctor_id integer references doctor(doctor_id) not null,
dnum integer references department(dnum) not null
)
``` | Foreign key referring to more than one primary key values(from one table) - Oracle SQL PLUS | [
"",
"sql",
"database",
"oracle",
""
] |
This is the only error I get. Please Help. Thank you in advance.
After I successfully created and a stored procedure in SQL Server. I tried to execute it with the following (example only)
```
exec [dbo].ExportResourceTime 'ABC111', '', 3, 1, '2013-10-01', '2013-10-30', 1, 21
```
Then I get the following error. See a... | There are 23 columns in your `#ItemisedTimeandMaterials` temporary table while you are inserting only 22 values from select list.
When inserting into table with large number of columns with computed values from SELECT list, you can keep track of columns by giving alias name to each computed column same as the target t... | try this
```
if @ResourceID <> ''
begin
insert into #Resources (ResourceID,OrganizationID,EffectiveDate)
Select ro.ResourceID,
ro.OrganizationID,
ro.EffectiveDate
from ResourceOrganization ro
inner join (select ResourceID,
... | Stored Procedure Insert Error: Column name or number of supplied values does not match table definition | [
"",
"sql",
"sql-server",
""
] |
I have a database table which stores ids of employees and their previous projects they have been working on. Now I want to retrieve pairs of employees that have been working on the same projects and amount of common projects between these two employees.
If I do "self-join" approach then I get duplicate rows.
```
SELEC... | add `ep1.employee_id >= ep2.employee_id` to the where clause. | I would create a new table with a unique index over the columns that you want to keep unique. Then do an insert from the old table into the new, ignoring the warnings about duplicated rows. Lastly, I would drop (or rename) the old table and replace it with the new table. In MySQL, this would look like
```
CREATE TABLE... | How-to get rid of duplicates in SQL query | [
"",
"sql",
""
] |
From the table below
```
date description amount
29/12/13 <13363000054123>JIT BAHADUR LAMICHHANE CR 10,000.00 TBI 29/12/13 29/12/13
29/12/13 <13363740800138>MAN BAHADUR . CR 1,19,595.00 TBI 29/12/13 29/12/13
29/12/13 <555349... | Try the combination of CHARINDEX and SUBSTRING. Assuming amount has format 'xxx.xx'
```
SELECT date,
LEFT(description, Charindex ('>', description)),
LEFT(amount, Charindex ('.', amount))
+ Substring(amount, Charindex ('.', amt)+1, 2)
FROM tbl
``` | This produce the information you have stipulated.
```
Declare @S varchar(50)
Declare @T varchar(50)
Select @S = '<13363000054123>JIT BAHADUR LAMICHHANE', @T = 'CR 10,000.00 TBI 29/12/13 29/12/13'
Select SUBSTRING(@S, 1, PATINDEX('%>%', @S)), SUBSTRING(@T, 1, PATINDEX('% TBI%', @T))
```
Use this in your query
```
Se... | substring in sql server 2008 | [
"",
"sql",
"sql-server",
"t-sql",
""
] |
I'm learning database and I have a question,
When I run the following query to give me 12 month Average Salary,
```
SELECT `EmployeeNo`,(`Salary`/12,) as AverageSalary FROM Employee
```
The salary that it returns is like 7787.000992213
How can i round the value? | If you want the number truncated, do this, using `TRUNCATE`:
```
SELECT `EmployeeNo`,TRUNCATE((`Salary`/12,),0) as AverageSalary FROM Employee
```
If you want it rounded to the nearest integer, do this, using `ROUND`:
```
SELECT `EmployeeNo`,ROUND(`Salary`/12,) as AverageSalary FROM Employee
``` | [ROUND(X), ROUND(X,D)](http://dev.mysql.com/doc/refman/5.0/en/mathematical-functions.html#function_round) - Rounds the argument X to D decimal places
For your example:
```
SELECT `EmployeeNo`, ROUND(`Salary`/12) as AverageSalary FROM Employee
``` | how to Round a value in SQL? | [
"",
"mysql",
"sql",
"database",
"phpmyadmin",
""
] |
Please help,
I'm trying to pivot sql server table like this:

To get something like this:

I've tried to do that in excel but it didn't work for me as it's duplicating attributes ... | SQL Server's `pivot` only works if you pivot on one column. Since you're pivoting on `(Item Id, Lot Number)`, you have to do it the old fashioned way:
```
select [Item Id]
, [Lot Number]
, sum(case when Attribute = 'PPA' then Value end) as PPA
, sum(case when Attribute = 'PU0' then Value end) as PU0... | See @Andomar's answer for writing a SQL query to do the pivot. But if you just want to use Excel it should work fine putting ItemId and Lot Number in rows, put Attribute in column section and Value in data section. You'll need to remove all the subtotal rows that Excel likes to add, which you do from the Properties of ... | Pivot table with specific logic query | [
"",
"sql",
"sql-server",
"excel",
"sql-server-2008",
"pivot-table",
""
] |
I want all student list which have `> 0` marks in asc order and then all 0 marks student.
I made a query for this, but this not give correct response:
```
(SELECT * FROM tbl_student WHERE marks>0)
UNION
(SELECT * FROM tbl_student WHERE marks=0)
```
after union this merge the data.
Kindly suggest me, what should I do... | Try this:
`SELECT * FROM tbl_student ORDER BY CASE WHEN marks = 0 THEN 9999 ELSE marks END ASC` | Try this
```
SELECT * FROM
tbl_student ORDER BY
CASE WHEN marks = 0
THEN 9999 ELSE marks
END
```
Instead of 9999 you can give your maximum number | Sql query to get result in asc order but 0 values should be last after all data | [
"",
"sql",
""
] |
I need to combine both select statements into one select
```
SELECT count(tbl_employer_post_details.employer_id) pending
FROM tbl_employer_post_details,
tbl_employer_registration
WHERE job_status=0
AND tbl_employer_registration.employer_id =
tbl_employer_post_details.... | Try this:
```
SELECT SUM(job_status = 0) pending, SUM(job_status = 1) approved
FROM tbl_employer_post_details epd
INNER JOIN tbl_employer_registration er ON epd.employer_id = er.employer_id
WHERE job_status IN (0, 1);
``` | Try it this way
```
SELECT SUM(job_status = 0) pending,
SUM(job_status = 1) approved
FROM tbl_employer_post_details d JOIN tbl_employer_registration r
ON r.employer_id = d.employer_id
WHERE job_status IN (0, 1)
``` | Count same id column with different condition in same select statement | [
"",
"mysql",
"sql",
"sql-server",
"select",
"count",
""
] |
How do I change my column's default value from None to something else? For example, I want my dates to have a default value of 0000-00-00 if I don't specify one when I create the row.
I understand this in phpMyAdmin, but I'm not sure how to do it via command prompt.
I also understand how to do this when adding a colu... | Use **ALTER TABLE** to **CHANGE** or **MODIFY** the **DEFAULT** value of column. Check this link [**ALTER TABLE SYNTAX**](http://dev.mysql.com/doc/refman/5.5/en/alter-table.html)
```
ALTER TABLE `tableName` CHANGE `columnName` `columnName` DATE DEFAULT '0000-00-00';
ALTER TABLE `tableName` MODIFY `columnName` DATE DE... | try this
```
ALTER TABLE foobar_data CHANGE COLUMN col VARCHAR(255) NOT NULL DEFAULT '{}';
```
user CHANGE to alter a existing column
see [Link](http://dev.mysql.com/doc/refman/5.1/en/alter-table.html) | MySQL - How to modify column default value? | [
"",
"mysql",
"sql",
"default",
"alter",
""
] |
I am passing my parameter as 'Suburbun','Indigo' to retrieve records matching both Campaigns in below Stored Procedure created in MySql.
```
CREATE PROCEDURE `DemoSP`(Campaign VARCHAR(3000))
BEGIN
SET @query = CONCAT('Select * from vicidial_log WHERE campaign_id IN (?)');
PREPARE stmt FROM @query;
SET @Campaig... | You won't be able to use `USING` in this case. You can just build the full query sting and execute it without parameters
```
DELIMITER $$
CREATE PROCEDURE DemoSP(Campaign VARCHAR(3000))
BEGIN
SET @query = CONCAT('SELECT * FROM vicidial_log WHERE campaign_id IN (', Campaign, ')');
PREPARE stmt FROM @query;
EXECUT... | Try this:
There is no need to use `PREPARE STATEMENT`. You can get the result using `FIND_IN_SET()` function
```
SELECT * FROM vicidial_log WHERE FIND_IN_SET(campaign_id, Campaign)
``` | IN Clause dont work in MySQL for me | [
"",
"mysql",
"sql",
"select",
"in-clause",
"find-in-set",
""
] |
I have two tables in different databases (WAMP server) with the same structure. I want to copy from the first database (`newkt`) to the second one (`oldkt`) all rows that do not exist in the second database (`oldkt`).
```
newkt -> table : users (1500 records) (id, name, password)
oldkt -> table : users (1200 recor... | You can do like the following:
```
insert into database1.table select * from database2.table where id not in(select id from database1.table);
``` | As said you should be able to perform a typical insert but by specifying the database name in the query:
```
SELECT *
INTO TargetDatabase.dbo.TargetTable
FROM SourceDatabase.dbo.SourceTable
``` | How to copy rows from one MySQL database to another | [
"",
"mysql",
"sql",
""
] |
So I have 6 Tables.
```
Company (1..1) --- (0..n) District
District (1..1) --- (0..n) City
City (1..1) --- (0..n) Employee
```
So alot of 1 on n relation's to start off.
Then I have 1 n..n relation implemented like this:
```
Employee (1..1) --- (0..n) EmpLang
EmpLang (0..n) --- (1..1) Lang
```
Now I select T... | Approach it with a sub query. In your where statement, you can do where employee.id in (select...)
the select statement here will select all employee\_id's that meet that language.
```
where ...
and employeeid in (select employeeID
from employee
left join Emplang on Employee.id = EmpLang.eid
left join land on Emp... | I think in this instance you may want to look at doing a join. You can learn more about joins if you are not familiar with them at this link: <http://www.codinghorror.com/blog/2007/10/a-visual-explanation-of-sql-joins.html>
EDIT: I can't post the code now (at work) but if nobody else has responded by the time I get ho... | Sql issue with selecting data | [
"",
"mysql",
"sql",
""
] |
I am migrating my database from sqlserver to mysql
when i come to `getDate()` function in sqlserver the replacement in mysql is `Now()`
but `Now()` not returned the exact result and format that `getDate()` returned.
Is there any solution to tweak the `Now()` result to make as same as `getDate()`
```
getDate() result ... | I overcome the problem of microsecond by usage of
```
sysdate(3) returned '2014-01-07 10:52:07.252'
```
Thanks for every one suggestions. | > The difference between the two functions is the milliseconds.
> Try converting
> the getdate() to exclude milliseconds. | Now() vs GetDate() | [
"",
"mysql",
"sql",
"sql-server",
""
] |
I have a Table Abstract, which has one of the columns (SerialNumber). It is having data as below.
```
1
1.1
1.1.1
1.1.2
1.2
..
..
10
10.1
10.2
```
Now, my requirement is to sort the data based on this column as first preference.
Maximum of 2 "dots" are possible in a SerialNumber.
So `1.2.3.4` is not possible. Maximu... | Function to extract every number using `'.'` as delimiter and lpad with 0s. And call the function() in `order by`
```
CREATE OR REPLACE FUNCTION FORMAT_MY_SERIAL(
ORIG_SERIAL VARCHAR2)
RETURN VARCHAR2
AS
FINAL_SERIAL VARCHAR2(15) := '';
SERIAL VARCHAR2(15);
BEGIN
SERIAL := ORIG_SERI... | I would probably use a regex function to split each part for ordering. Something like:
```
select serialnumber
from data
order by
to_number(regexp_substr(serialnumber, '[[:digit:]]+')),
to_number(regexp_substr(serialnumber, '[[:digit:]]+', 1, 2)) nulls first,
to_number(regexp_substr(serialnumber, '[[:digit... | Custom sort with series of numbers(sequences) using oracle sql | [
"",
"sql",
"oracle",
""
] |
the problem is:
I have two tables(column names are in brackets):
Cars (CarColorId, CarName), CarColor (CarColorId, CarColorName);
The task is to UPDATE Cars.CarName with a string "\_updated" but only if CarColor.CarColorName = 'red'. I have know idea how to do this without joins
I have tried this way:
```
UPDATE Ca... | You can try any one of this in Oracle
**Normal Update**
```
UPDATE
CARS
SET
CARS.CARNAME =
CONCAT ( CARS.CARNAME,
'_updated' )
WHERE
EXISTS
(SELECT
CARCOLOR.CARCOLORID
FROM
CARCOLOR
WHERE
CARS.... | You can modify your query like this:
```
UPDATE
Cars
set
CarName = concat (CarName, '_updated')
WHERE
CarColorId in (
select
CarColorId
from
CarColor
where
CarColorName='red'
)
;
``` | Oracle database. How to update selected columns. | [
"",
"sql",
"oracle",
""
] |
I have a mysql table with some weird id's like this:
```
╔═══╦════════════╦═════════════╦═══════════╦═════════════╦═══════════╗
║ ║ id ║ user_id ║ hours_a ║ hours_b ║ hours_c ║
╠═══╬════════════╬═════════════╬═══════════╬═════════════╬═══════════╣
║ 1 ║ 010120149 ║ 9 ║ 10 ║ ... | Try this:
```
SELECT *, (hours_a + hours_b + hours_c) totalHours
FROM weird_table
WHERE user_id = 9 AND
STR_TO_DATE(SUBSTRING(id, 1, 8), '%d%m%Y') BETWEEN '2014-01-01' AND '2014-01-31'
```
**OR**
```
SELECT *, (hours_a + hours_b + hours_c) totalHours
FROM weird_table
WHERE user_id = 9 AND SUBSTRING(id, 3, ... | You can try this
```
select userid,SUBSTRING(id, 3, 2) ,SUBSTRING(id, 5, 4),hours_a,hours_b, hours_c
FROM weird_table
WHERE userid = 9 AND SUBSTRING('010120149', 3, 6) = '012014';
```
and the retrived rows hours value can be simply added up. | PHP: Parse all data from mysql where the 3rd and 4th digit of the id | [
"",
"mysql",
"sql",
"datetime",
"select",
"substring",
""
] |
I have a table which shows me my users' downloads reports.
The table looks like this:
```
╔═══╦════════════╦═════════════╗
║ ║ url ║ user ║
╠═══╬════════════╬═════════════╣
║ 1 ║ Bla ║ 1 ║
║ 2 ║ Bla Bla ║ 1 ║
║ 3 ║ Bla Bla Bla║ 1 ║
║ 4 ║ Bla2 ║ 2 ... | You can use a `WHERE` clause with a combination of `GROUP BY` and `HAVING` to get the result:
```
select user
from yourtable
where url in ('Bla', 'Bla Bla')
group by user
having count(distinct url) = 2;
```
See [SQL Fiddle with Demo](http://sqlfiddle.com/#!2/5c218/2) | You can use a self join
```
select u.user
from links u
join links u1 on(u.`user`=u1.user)
where u1.url ='Bla'
and u.url= 'Bla Bla'
```
[**Fiddle**](http://sqlfiddle.com/#!2/daa6a6/1) | SQL Condition With Multiple Rows | [
"",
"mysql",
"sql",
"select",
""
] |
I am trying to run a query in SQL Server 2008 and it's running very slowly when I change the value of one of the variables (`SourceID`). The below code works fine when the `SourceID` is set to another available ID but on the one in the code it just hangs... for hours if I let it!
The `email`, `dupe` and `MyMystery` co... | I suspect [statistics](http://sqlhint.com/sqlserver/how-to/when-update-statistics-flag-2371) for a\_customer\_test table are not up-to-date. Execute this in order to update them:
```
UPDATE STATISTICS a_customer_test;
``` | The best thing to do would be to removed the where clause from the CTE and place it on the ON clause (Only do this with INNER JOINs not LEFT JOIN).
The reason is when a Join is made, the conditions on the ON CLAUSE are made at the time of the join and eliminates a lot of the useless data while the data is being put on ... | SQL query running very slow | [
"",
"sql",
"sql-server",
"performance",
"sql-server-2008",
"t-sql",
""
] |
I have a table with a column of type `xml`. I'd like to wrap the result set in a parent tag.
For example:
Here is the table result set:
```
SELECT *
FROM MyColorTable
```
Result :
```
<Color>Red</Color>
<Color>Orange</Color>
<Color>Yellow</Color>
<Color>Green</Color>
<Color>Blue</Color>
<Color>Indigo</Color>
<Colo... | 1) **Updated solution:**
```
DECLARE @MyTable TABLE (Col1 XML);
INSERT @MyTable VALUES (N'<Color>Red</Color>');
INSERT @MyTable VALUES (N'<Color>Orange</Color>');
INSERT @MyTable VALUES (N'<Color>Yellow</Color>');
INSERT @MyTable VALUES (N'<Color>Blue</Color>');
INSERT @MyTable VALUES (N'<Color>Green</Color>');
INSERT... | The SQL Server has a good build-in support for work with XML. There is no need to store a `XML tag` in your column.
You should remove the unnecessary `<Color>` tag in order to optimize the work with XML and reduce the column storage - it is easy to generate it when it is needed like this:
```
SELECT [color]
FROM Data... | I need to wrap a result set of xml data with a parent tag | [
"",
"sql",
"sql-server",
"xml",
"t-sql",
""
] |
I've a table what looks like that:
```
ID | title | author | timestamp | livetime | special
```
My goal is select all from table where livetime is larger than current timestamp and order it by timestamp desc BUT records where "special" is true must be in first (of course, also ordered). It's possible to do only with ... | Yes, you can sort by two columns. Value of true is 1 and false 0, so you need to sort in the descending order.
```
SELECT * FROM ads WHERE livetime > UNIX_TIMESTAMP() ORDER BY special DESC, timestamp DESC
``` | ```
SELECT * FROM ads
WHERE livetime > UNIX_TIMESTAMP()
ORDER BY special <> 1,
timestamp DESC
``` | Order by date but add important at first in MySQL | [
"",
"mysql",
"sql",
""
] |
Should I be creating and dropping intermediate tables in hive?
I can write something like (much simplified):
```
drop table if exists tmp1;
create table tmp1 as
select a, b, c
from input1
where a > 1 and b < 3;
drop table if exists tmp2;
create table tmp2 as
select x, y, z
from input2
where x < 6;
drop table if exi... | There is one significant difference.
Running the one big query will allow the optimizer more freedom in optimizations.
One of the most important optimizations in such cases are paralellims as set in `hive.exec.parallel`. when set to true hive will exexcute independant stages in parallel.
In your case, in the 2nd ... | I like to create multiple views, and then only create a table at the end. This allows the Hive optimizer to reduce the number of map-reduce steps, and execute in parallel as dimamah and Nigel have pointed out, but helps maintain readability for very complicated pipelines.
For your example, you could replace it with
`... | Hive SQL coding style: intermediate tables? | [
"",
"sql",
"hadoop",
"hive",
""
] |
By using the following query, temporary table `testingTemp` will be created and the definition of columns are depending on `oriTable`.(I guess)
```
Select a.ID AS [a],
b.ID AS [b],
c.ID AS [c]
INTO #testingTemp
FROM
oriTable
```
And I have my second query as below:
```
Insert into #testingTemp (c)
Se... | Use
```
SELECT ID + 0 AS [a],
ID + 0 AS [b],
ID + 0 AS [c]
INTO #testingTemp
FROM oriTable
```
The nullability of columns computed via an expression is almost always assumed to be `NULL` rather than `NOT NULL` | try this:
```
ALTER TABLE #testingTemp ALTER COLUMN [a] int NULL
``` | SQL Server possible to create temp table with all columns nullable automatically? | [
"",
"sql",
"sql-server",
""
] |
I have a table in a SQL Server database looking like this:
```
+-----+-----+-----+-----+
| ID | A | B | C |
+=====+=====+=====+=====+
| 1 | 1 | 1 | 6 |
| 2 | 1 | 2 | 7 |
| 3 | 1 | 3 | 3 |
| 4 | 2 | 1 | 6 |
| 5 | 2 | 2 | 7 |
| 6 | 2 | 3 | 8 |
| 7 | 3 | 1 | 6... | Here is an answer that works with repeated values, [fiddle here](http://sqlfiddle.com/#!3/96cbd/11)
```
SELECT
[t].[id], [t].[a], [t].[b], [t].[c]
FROM
[Temp] [t]
JOIN (
SELECT
[b], [c]
FROM (
SELECT DISTINCT
[a], [b], [c]
FROM
... | Are you looking for the below query.?
and
please tell me if i have missed out something.
```
declare @tab1 table (id int,a int,b int, c int)
insert into @tab1 values (1,1,1,6),(2,1,2,7),(3,1,3,3),(4,2,1,6),(5,2,2,7),(6,2,3,8),(7,3,1,6),(8,3,2,9),(9,3,3,10),(10,4,4,4)
select * from @tab1
```
Code Part
```
select
... | Complicated SQL Search for duplicates | [
"",
"sql",
"sql-server",
""
] |
I'm looking to do a SQL output with most updated price of product. The product\_price can be updated multiple times for the product number, therefore creating more than one row. I'm looking to eliminate more than one row per product\_number.
```
SELECT
product_number
,product_price
,MAX(update_timestamp)
FROM pro... | There are a couple ways of doing this. My preferred is a subquery. First get the product number and it's maxtimestamp:
```
SELECT product_number
,MAX(update_timestamp) as maxtimestamp
FROM product_price
group by product_number
```
Now turn that into a subquery and inner join it to the first table to filter all but ... | Assuming that you want the last updated price *for each product*, then try this:
```
SELECT
Ranked.product_number,
Ranked.product_price,
Ranked.update_timestamp
FROM
(
SELECT
pp.product_number,
pp.product_price,
pp.update_timestamp,
DENSE_RANK() OVER (
PARTITION BY pp.product_number
... | Trying to Eliminate Duplicate Rows SQL Query | [
"",
"mysql",
"sql",
""
] |
I have 2 Tables in SQL server 2008 r2
```
+----+-----------------+
| id | txt |
+----+-----------------+
| 1 | {115467}Ruwan |
| 2 | {7877878787}pat |
+----+-----------------+
```
and
```
+----+------------+
| id | pid |
+----+------------+
| 1 | 115467 |
| 2 | 7877878787 |
| 3 | 7878... | Try this:
```
SELECT t1.id, t1.pid, (CASE WHEN t2.id IS NULL THEN 'no' ELSE 'yes' END) matches
FROM temp2 t1
LEFT OUTER JOIN temp t2 ON t2.txt LIKE '%{' + CAST(t1.pid AS VARCHAR(10)) + '}%'
```
Check the [**SQL FIDDLE DEMO**](http://sqlfiddle.com/#!3/80665/1)
**OUTPUT**
```
| ID | PID | MATCHES |
|----|----... | try this
```
select
t2.id,
t2.pid,
CASE
when t1.txt is NULL THEN 'no'
ELSE 'YES'
END AS matches
from t2
left join t1
on (t1.txt like '%{'+t2.pid+'}%')
```
result
```
id pid matches
1 115467 YES
2 7877878787 YES
3 78787878 no
``` | using dynamic string like | [
"",
"sql",
"sql-server",
"select",
"left-join",
"case",
""
] |
I've searched over the internet but couldn't find a way to resolve my issue. My query is something like that
```
SELECT users.id, SUBSTRING(posts.datestr, 4, 8)
FROM users, posts
WHERE posts.datestr='Jan-2014'
```
(That query above was shortened)
The value in posts.datestr is actually `20-Jan-2014`, but I want it ... | You need to alias the result of the `SUBSTRING` and use that alias in your conditions (`shortdate` in the example below)
Since you'll now be using an alias in your conditions, you can't use the `where` clause, you can though use the `having` clause
something like:
```
SELECT users.id, SUBSTRING(posts.datestr, 4, 8) ... | Use [**DATETIME**](http://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_date-format) function instead of **SUBSTRING()**
```
SELECT users.id, DATE_FORMAT(STR_TO_DATE(posts.datestr, '%d-%b-%Y'), '%b-%Y') updatedDate
FROM users, posts
HAVING updatedDate = 'Jan-2014'
``` | MySQL Substring with WHERE | [
"",
"mysql",
"sql",
"select",
"substring",
"date-format",
""
] |
I am building out an app that have different types of "posts" and a user can insert as many of these as they like. The posts though can be of different types, for example an image post, video post, text post etc... and obviously these will all have different fields in the database. An example would be that the image ty... | The natural way to model what you're doing here is by mapping an inheritance hierarchy into your relational schema.
What you want is to take all the common elements of all posts (post\_id, date\_created, user\_id, etc.) plus a `type` field and you make that your 'base' table. This table represents all `posts` regardle... | While you could have separate tables for each post type , I cannot think of any reason against using just one table :
> posts
```
post_id
post__type -- Ex. 1: Text ,2: Image ,3: Video .
post__user_id
post__datetime
post__title -- Images and Videos probably could have titles as well .
post__content -- This get... | Database design help - Splitting out tables | [
"",
"mysql",
"sql",
"database",
"database-design",
""
] |
I have a query (with the purpose of making a view) which is using a few joins to get each column. Performance degrades quickly (exponentially?) for each set of joins added.
What would be a good approach to make this query faster? Please see comments within the query.
If it helps, this is using the WordPress DB schema... | Your performance issue is most likely caused by the join with the 'term\_taxonomy' table.
All other joins seems to use the primary key (where you probobly have working indexes on).
So my suggestion is to add a compound index on **term\_taxonomy\_id** and **term\_id** (or if you must: **taxonomy**). Like this:
... | Make Sure all the columns on which there is "ON" conditional statements is there, should be indexed.
This will significantly improve the speed. | How to Improve Query Performance with many JOINs | [
"",
"mysql",
"sql",
"performance",
"select",
"query-optimization",
""
] |
I have table which looks like this
```
+----------------------------+
| id | bdate | item |
+----------------------------+
| 1 | 20010101 | 1a |
| 1 | 20020202 | 1b |
| 1 | 20030303 | 1c |
| 2 | 20010101 | 1d |
| 2 | 20020202 | 1e |
+-------------------------... | Do it this way
```
UPDATE t
SET bdate = GETDATE()
FROM table1 t LEFT JOIN
(
SELECT id, MAX(bdate) bdate
FROM table1
GROUP BY id
) e
ON t.id = e.id
AND t.bdate = e.bdate
WHERE e.id IS NULL;
```
Outcome:
```
| ID | BDATE | ITEM |
|----|------------|------|
| 1 | 2014-01-06 | 1a |
| 1 | ... | I am assuming here that you already built your table with the data (as per your example).
Let's say you name your table "MainTable", my take would be the following :
```
UPDATE MT
SET bdate = CASE WHEN MT2.bdate IS NULL THEN GETDATE() ELSE MT2.bdate END
FROM MainTable AS MT
LEFT JOIN (
SELEC... | Update multiple rows from group by SQL | [
"",
"sql",
"sql-server",
""
] |
I'm unable to declare a mysql variable inside a stored procedure. Also i cannot open a cursor as well i keep getting the same error:
> ERROR 1064 (42000): You have an error in your SQL syntax; check the
> manual that corresponds to your MySQL server version for the right
> syntax to use near '@userID INT;
> DECLARE @c... | 1. As it has already been mentioned by others you're mixing local variables (without `@` in front of a variable name) and user(session) variables (that have `@` in front of a variable name). `DECLARE` is used **only** for local variables. Session variables are always available and don't require declaration.
2. It a goo... | Try this
```
use phpBank;
DELIMITER //
CREATE PROCEDURE newUser()
BEGIN
DECLARE @userID int;
DECLARE @cursorUserID AS CURSOR;
SET @cursorUserID = CURSOR FOR SELECT (MAX(userID) + 1) FROM Users;
OPEN @newUserID;
END;
//
DELIMITER ;
``` | Cannot declare a variable in a stored procedure | [
"",
"mysql",
"sql",
"stored-procedures",
""
] |
I've created sqlfiddle to try and get my head around this <http://sqlfiddle.com/#!2/21e72/1>
In the query, I have put a `max()` on the compiled\_date column but the recommendation column is still coming through incorrect - I'm assuming that a select statement will need to be inserted on line 3 somehow?
I've tried the... | As others have pointed out, the issue is that some of the select columns are neither aggregated nor used in the group by clause. Most DBMSs won't allow this at all, but MySQL is a little relaxed on some of the standards...
So, you need to first find the `max(compiled_date)` for each case, then find the recommendation ... | Thank you for providing sqlFiddle. But only reporting data is given. we highly appreciate if you give us sample data of whole tables.
Anyway, Could you try this?
```
SELECT
`case`.number,
staff.staff_name AS ``case` owner`,
client.client_name,
`case`.address,
x.mx_date,
report.recommendation
F... | MAX() Function not working as expected | [
"",
"mysql",
"sql",
"select",
"group-by",
"max",
""
] |
I got this simple join statement and I'm pretty sure the syntax is correct. I looked some tutorials and I don't find any difference between my code and the exemples.
Here's the statement:
```
SELECT n.id nId, n.news_date, n.news_type,
p.id pId, p.title pTitle, p.file_path pPath,
s.id sId, s.title sTitle,... | Probably you are looking for something like this to return data for the record in photo news with data in at least one of the other table.
In that case you need to use a LEFT JOINs and not OR in the JOIN conditions.
```
SELECT n.id nId, n.news_date, n.news_type,
p.id pId, p.title pTitle, p.fi... | Try this, You made mistake in JOINing tables.
[for reference you can see how multiple tables are JOINed together.](https://stackoverflow.com/a/8974371/435559)
```
SELECT n.id nId, n.news_date, n.news_type,
p.id pId, p.title pTitle, p.file_path pPath,
s.id sId, s.title sTitle, s.content sContent,
v... | MySQL inner join fails | [
"",
"mysql",
"sql",
"join",
"inner-join",
""
] |
I tried this in two ways (I think they are the same):
```
select product.maker,speed from product,laptop
where product.model=laptop.model and hd>='10'
```
and
```
select product.maker, speed from laptop
join product
on (product.model=laptop.model)
where hd>='10'
```
and I receive this in the simulator:
> "Your que... | select distinct product.maker, speed from laptop
join product
on (product.model=laptop.model)
where hd>='10'
or
select distinct product.maker,speed from product,laptop
where product.model=laptop.model and hd>='10' | *When this answer was written, one query used `hd>=10` and one used `hd>='10'`. The query has since been edited.*
When you use the `'10'` in the comparison, you cause the DBMS to do the comparison as a string instead of as a number. Under string comparison, `9` is greater than `10`.
As a general rule of thumb, if the... | Point out the maker and speed of the laptops having hard drive capacity more or equal to 10 Gb | [
"",
"sql",
""
] |
How can I find, from within a single table, customer names with orders greater than $2000 ?
```
Customer :
custName custOrderVal
A 100
B 200
A 900
C 2400
A 1100
B 8000
```
`select cust.custName from customer cust where cust.custOrderVal > 2000;` will not show the correct da... | **Query**
```
DECLARE @t TABLE (custName VARCHAR(10),custOrderVal INT)
INSERT INTO @t
VALUES
('A',100), ('B',200),('A',900),('C',2400),
('A',1100),('B',8000),('D',1000),('F',500)
SELECT CustName
FROM @t
GROUP BY CustName
HAVING SUM(custOrderVal) > 2000
```
**Result Set**
```
╔══════════╗
║ CustName ║
╠══════════╣
... | By using `HAVING` clause, like this:
```
SELECT custName
FROM Customer
GROUP BY custName
HAVING SUM(custOrderVal) > 2000
```
You need to use `GROUP BY` to get the `SUM` per customer and then use `HAVING` to limit the result (just like a `WHERE` clause). | How to find customer with orders greater than X from single table | [
"",
"mysql",
"sql",
""
] |
```
ALTER PROCEDURE [dbo].[K_FS_GetFeedDivisionReport]
@orderno varchar(50)
AS
BEGIN
SET NOCOUNT ON;
select OT.OrderNo,FT.Feedtype,ModeofPack='Plastic',BG.Bagtype,OD.Numofbags,
(OD.numofbags*BG.Bagtype) as TotalQty,sum(TotalQty) as Total from
K_FS_OrderconfirmDetails OD
inner join K_FS_bagtype BG on OD.bagtype=B... | yes, you can do it like this :
```
ALTER PROCEDURE [dbo].[K_FS_GetFeedDivisionReport]
@orderno varchar(50)
AS
BEGIN
SET NOCOUNT ON;
select OT.OrderNo,FT.Feedtype,ModeofPack='Plastic',BG.Bagtype,OD.Numofbags,
(OD.numofbags*BG.Bagtype) as TotalQty,sum(OD.numofbags*BG.Bagtype) as Total from
K_FS_OrderconfirmDetail... | You can achieve this using sub query.
Modify your select statement this way:
```
select OT.OrderNo,FT.Feedtype,ModeofPack='Plastic',BG.Bagtype,OD.Numofbags,
(OD.numofbags*BG.Bagtype) as TotalQty,
(select SUM(OD.numofbags*BG.Bagtype)
from K_FS_OrderconfirmDetails OD inner join
K_FS_b... | sum clause method calculating the total with alias name? | [
"",
"sql",
"sql-server",
"sql-server-2008",
""
] |
Hi I am new to the Database, and i am trying to get the records from the multiple tables, but depending upon there selection following is my tables
```
Table1
Column1 Column2
1 10
2 25
3 23
4 15
5 7
Table2
Column1 Co... | Please use the Below Code and Try
```
select * from table1 where column1 not in ( select column1 from table2 union select column1 from table3)
union
select * from table2 where column1 not in (select column1 from table3)
union
select * from table3
``` | ```
SELECT t1.column1, COALESCE(t3.column2,t2.column2,t1.column2)
FROM t1
LEFT JOIN t2 on t1.column1=t2.column1
LEFT JOIN t3 on t1.column1=t3.column1
``` | How to get the records from multiple tables? | [
"",
"sql",
"sql-server",
"sql-server-2008",
"join",
"outer-join",
""
] |
I have a table that lists items and a status about these items. The problem is that some items have multiple different status entries. For example.
```
HOST Status
1.1.1.1 PASS
1.1.1.1 FAIL
1.2.2.2 FAIL
1.2.3.3 PASS
1.4.2.1 FAIL
1.4.2.1 FAIL
1.1.4.4 NULL
```
I need t... | Try using a `case` statement to convert to ordered results and group on that, finally, you'll need to convert back to the nice, human-readable answer:
```
with cte1 as (
SELECT HOST,
[statNum] = case
when Status like 'PASS' then 2
when Status like 'FAIL' then 1
... | You can use `Max(Status)` with `Group by Host` to get `Distinct` values:
```
Select host, coalesce(Max(status),'No results') status
From Table1
Group by host
Order by host
```
**[Fiddle Demo Results:](http://sqlfiddle.com/#!6/e0f4a/4)**
```
| HOST | STATUS |
|---------|------------|
| 1.1.1.1 | PASS |
|... | SQL Conditional Case | [
"",
"sql",
"sql-server",
"t-sql",
"case",
"distinct-values",
""
] |
Ive been looking at several articles on stack but not been exactly specific to what I need
I have a table with application names, teams, service, directorate and username
I want to bring back the application name, team, service, directorate back of the highest used location (team, service, directorate) based on user,... | You can use the Analytic function [RANK](http://technet.microsoft.com/en-us/library/ms176102.aspx) to put your team/service/directorate combination in order of number users by Application Name, then just select the top one for each. The key is that `ApplicationName` appears in the group by clause but not in the Partiti... | ```
SELECT TOP(1)
[ApplicationName]
,[Team]
,[Service]
,[Directorate]
,count(distinct username) Usercount
FROM [Windows7data].[dbo].[devices_users_apps_detail] a
group by
[ApplicationName]
,[Team]
,[Service]
,[Directorate]
order by
Usercount desc;
... | SQL group by max count | [
"",
"sql",
"sql-server",
""
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.